#include "pwmi.h"

static void PWMI_CPIO_Config(void)
{
    GPIO_InitTypeDef GPIO_InitStructure;

    // 使能GPIOA时钟
    RCC_APB2PeriphClockCmd(PWMI_GPIO_CLK, ENABLE);

    // 配置GPIOA0为上拉输入模式
    GPIO_InitStructure.GPIO_Pin = PWMI_GPIO_PIN;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_Init(PWMI_GPIO_PORT, &GPIO_InitStructure);
}

static void PWMI_TIM_Config(void)
{
    TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
    TIM_ICInitTypeDef TIM_ICInitStructure;

    // 使能TIM3时钟
    RCC_APB1PeriphClockCmd(PWMI_TIM_CLK, ENABLE);

    // 配置TIM3时基单元
    TIM_TimeBaseStructure.TIM_Period = 65536 - 1;               // 满量程计数
    TIM_TimeBaseStructure.TIM_Prescaler = 72 - 1;               // 标准频率为72M/72=1MHz
    TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1;     // 不分频
    TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up; // 向上计数模式
    TIM_TimeBaseInit(PWMI_TIM, &TIM_TimeBaseStructure);

    TIM_ICInitStructure.TIM_Channel = PWMI_TIM_CHANNEL;               // 选择通道
    TIM_ICInitStructure.TIM_ICFilter = 0;                           // 不滤波
    TIM_ICInitStructure.TIM_ICPolarity = TIM_ICPolarity_Rising;     // 上升沿触发
    TIM_ICInitStructure.TIM_ICPrescaler = TIM_ICPSC_DIV1;           // 不分频
    TIM_ICInitStructure.TIM_ICSelection = TIM_ICSelection_DirectTI; // 选择直连通道
    TIM_PWMIConfig(PWMI_TIM, &TIM_ICInitStructure);

    TIM_SelectInputTrigger(PWMI_TIM, PWMI_TIM_INPUT_TRIGGER); // 选择从模式触发源
    TIM_SelectSlaveMode(PWMI_TIM, TIM_SlaveMode_Reset);     // 选择从模式为Reset

    TIM_Cmd(PWMI_TIM, ENABLE);
}

void PWMI_Init(void)
{
    PWMI_CPIO_Config();
    PWMI_TIM_Config();
}

uint32_t PWMI_GetFreq(void)
{
    return 1000000 / (TIM_GetCapture1(PWMI_TIM) + 1);
}

uint32_t PWMI_GetDuty(void)
{
    return 100 * (TIM_GetCapture2(PWMI_TIM) + 1) / (TIM_GetCapture1(PWMI_TIM) + 1);
}